import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Modal, Alert } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import I18n from '../utils/i18n';

const tasks1 = [
    I18n.t('tasks1.one'),
    I18n.t('tasks1.two'),
    I18n.t('tasks1.three'),
    I18n.t('tasks1.four'),
    I18n.t('tasks1.five')
];

const tasks2 = [
    I18n.t('tasks2.one'),
    I18n.t('tasks2.two'),
    I18n.t('tasks2.three'),
    I18n.t('tasks2.four'),
    I18n.t('tasks2.five')
];

const tasks3 = [
    I18n.t('tasks3.one'),
    I18n.t('tasks3.two'),
    I18n.t('tasks3.three'),
    I18n.t('tasks3.four'),
    I18n.t('tasks3.five')
];

const tasks4 = [
    I18n.t('tasks4.one'),
    I18n.t('tasks4.two'),
    I18n.t('tasks4.three'),
    I18n.t('tasks4.four'),
    I18n.t('tasks4.five')
];

const tasks5 = [
    I18n.t('tasks5.one'),
    I18n.t('tasks5.two'),
    I18n.t('tasks5.three'),
    I18n.t('tasks5.four'),
    I18n.t('tasks5.five')
];

const allTasks = [tasks1, tasks2, tasks3, tasks4, tasks5];

const encouragements = [
    I18n.t('encouragements.one'), I18n.t('encouragements.two'), I18n.t('encouragements.three'), I18n.t('encouragements.four'),
    I18n.t('encouragements.five'), I18n.t('encouragements.six'), I18n.t('encouragements.seven'),
    I18n.t('encouragements.eight'), I18n.t('encouragements.nine'), I18n.t('encouragements.ten')
];

const DailyTasks = ({ isVisible, onClose, currentMood }) => {
    const [tasks, setTasks] = useState([]);
    const [completedTasks, setCompletedTasks] = useState([]);

    useEffect(() => {
        if (isVisible) {
            loadTasks();
        }
    }, [currentMood, isVisible]);

    const loadTasks = async () => {
        try {
            const today = new Date().toDateString();
            const savedTasksInfo = await AsyncStorage.getItem('dailyTasksInfo');
            let tasksInfo = savedTasksInfo ? JSON.parse(savedTasksInfo) : null;

            if (!tasksInfo || tasksInfo.date !== today) {
                const daysSinceEpoch = Math.floor(Date.now() / (1000 * 60 * 60 * 24));
                const taskSetIndex = daysSinceEpoch % allTasks.length;

                tasksInfo = {
                    date: today,
                    tasks: allTasks[taskSetIndex],
                    completedTasks: []
                };

                await AsyncStorage.setItem('dailyTasksInfo', JSON.stringify(tasksInfo));
            }

            setTasks(tasksInfo.tasks);
            setCompletedTasks(tasksInfo.completedTasks);

        } catch (error) {
            console.error('Error loading tasks:', error);
        }
    };

    const toggleTask = async (index) => {
        const newCompletedTasks = [...completedTasks];
        const taskIndex = newCompletedTasks.indexOf(index);
        if (taskIndex > -1) {
            newCompletedTasks.splice(taskIndex, 1);
        } else {
            newCompletedTasks.push(index);
            showEncouragement(newCompletedTasks.length);
        }
        setCompletedTasks(newCompletedTasks);

        const tasksInfo = {
            date: new Date().toDateString(),
            tasks: tasks,
            completedTasks: newCompletedTasks
        };
        await AsyncStorage.setItem('dailyTasksInfo', JSON.stringify(tasksInfo));
    };

    const showEncouragement = (completedCount) => {
        if (completedCount === tasks.length) {
            Alert.alert(I18n.t('showEncouragement.title1'), I18n.t('showEncouragement.content1'));
        } else if (completedCount === Math.ceil(tasks.length / 2)) {
            Alert.alert(I18n.t('showEncouragement.title2'), I18n.t('showEncouragement.content2'));
        } else {
            const randomEncouragement = encouragements[Math.floor(Math.random() * encouragements.length)];
            Alert.alert(I18n.t('showEncouragement.title3'), randomEncouragement);
        }
    };

    return (
        <Modal
            visible={isVisible}
            animationType="slide"
            transparent={true}
            onRequestClose={onClose}
        >
            <View style={styles.modalContainer}>
                <View style={styles.modalContent}>
                    <Text style={styles.title}>{I18n.t('today_s_small_task_title')}</Text>
                    <ScrollView style={styles.taskList}>
                        {tasks.map((task, index) => (
                            <TouchableOpacity
                                key={index}
                                style={styles.taskItem}
                                onPress={() => toggleTask(index)}
                            >
                                <Text style={[
                                    styles.taskText,
                                    completedTasks.includes(index) && styles.completedTask
                                ]}>
                                    {task}
                                </Text>
                                {completedTasks.includes(index) && (
                                    <Icon name="checkmark-circle" size={24} color="#4CAF50" />
                                )}
                            </TouchableOpacity>
                        ))}
                    </ScrollView>
                    <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                        <Text style={styles.closeButtonText}>{I18n.t('close')}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
};

const styles = StyleSheet.create({
    modalContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContent: {
        backgroundColor: 'white',
        borderRadius: 20,
        padding: 20,
        width: '90%',
        maxHeight: '80%',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
        textAlign: 'center',
    },
    taskList: {
        marginBottom: 20,
    },
    taskItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#e0e0e0',
    },
    taskText: {
        fontSize: 16,
        flex: 1,
    },
    completedTask: {
        textDecorationLine: 'line-through',
        color: '#888',
    },
    closeButton: {
        backgroundColor: '#3498db',
        padding: 10,
        borderRadius: 5,
        alignItems: 'center',
    },
    closeButtonText: {
        color: 'white',
        fontSize: 16,
    },
});

export default DailyTasks;
